package com.test.mooan.labama.activity_fragment_boom.base_boom;

import static com.test.mooan.labama.constants_boom.Constant_boom.Process_Account;
import static com.test.mooan.labama.constants_boom.Constant_boom.Process_Ocr;
import static com.test.mooan.labama.constants_boom.Constant_boom.Process_Sefie;
import static com.test.mooan.labama.utils_boom.Permissionutil_boom.Permission_Code_Camera;
import static com.test.mooan.labama.utils_boom.Permissionutil_boom.Permission_Code_Sms;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.test.mooan.labama.R;
import com.test.mooan.labama.activity_fragment_boom.ln_boom.LnApplyActivity_boom;
import com.test.mooan.labama.activity_fragment_boom.ln_boom.LnMainActivity_boom;
import com.test.mooan.labama.activity_fragment_boom.ln_boom.RepaymentActivity;
import com.test.mooan.labama.activity_fragment_boom.login_boom.LoginPhoneNumActivity_boom;
import com.test.mooan.labama.activity_fragment_boom.login_boom.MobileVerificationActivity;
import com.test.mooan.labama.activity_fragment_boom.login_boom.MobileVerificationActivity2;
import com.test.mooan.labama.activity_fragment_boom.process_boom.BdBkActActivity_Cote_boom;
import com.test.mooan.labama.activity_fragment_boom.process_boom.BdBkActActivity_Fr_boom;
import com.test.mooan.labama.activity_fragment_boom.process_boom.FaceUploadActivity_boom;
import com.test.mooan.labama.activity_fragment_boom.process_boom.InfoUpldActivity_boom;
import com.test.mooan.labama.activity_fragment_boom.process_boom.OcrUpldActivity_boom;
import com.test.mooan.labama.bean_boom.config_info_boom.CountryInfo_boom;
import com.test.mooan.labama.bean_boom.process_boom.ProcessInfo_boom;
import com.test.mooan.labama.bean_boom.product.Product;
import com.test.mooan.labama.bean_boom.user_info_boom.LoginInfo_boom;
import com.test.mooan.labama.constants_boom.Constant_boom;
import com.test.mooan.labama.dialog_boom.AllPermissionDialog_boom;
import com.test.mooan.labama.dialog_boom.MsgDialog_boom;
import com.test.mooan.labama.dialog_boom.StatementDialog_boom;
import com.test.mooan.labama.utils_boom.Permissionutil_boom;
import com.test.mooan.labama.utils_boom.Threadutils_boom;
import com.test.mooan.labama.utils_boom.analytics_boom.util_boom.AnalyticsUtil_boom;
import com.test.mooan.labama.utils_boom.helper_boom.ActivityHelper_boom;
import com.test.mooan.labama.utils_boom.helper_boom.UserInfoHelper_boom;
import com.test.mooan.labama.utils_boom.http_boom.HttpManager_boom;
import com.test.mooan.labama.utils_boom.http_boom.HttpPresenter_boom;

import java.util.List;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;


public abstract class BaseActivity_boom extends AppCompatActivity implements EasyPermissions.PermissionCallbacks,EasyPermissions.RationaleCallbacks {

    private Toast toast_boom;

    public String pageTag;

    protected Product applyProduct;
    protected Product repayProduct;

    private AllPermissionDialog_boom allPermissionDialog;

    private static boolean permissionRequestFlag = false;

    private Runnable runnableWithCameraPermission;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //tag2025
//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
    }

    @Override
    protected void onResume() {
        super.onResume();

        HttpPresenter_boom.getInstance().setActivity(this);
        if (TextUtils.isEmpty(pageTag)) pageTag = getClass().getSimpleName();
        UserInfoHelper_boom.gInstance().addEventPoint((pageTag + "_START").toUpperCase());
    }

    @Override
    protected void onPause() {
        super.onPause();

        if (allPermissionDialog!=null && allPermissionDialog.isShowing()) return;

        HttpPresenter_boom.getInstance().setActivity(null);
        if (TextUtils.isEmpty(pageTag)) pageTag = getClass().getSimpleName();
        UserInfoHelper_boom.gInstance().addEventPoint((pageTag + "_END").toUpperCase());
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View view = getCurrentFocus();
            if (view != null) {
                if (ActivityHelper_boom.canHideKeyboard(view, ev)) {
                    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (inputMethodManager != null) {
                        ActivityHelper_boom.hideKeyboard(this);
                        EditText editText = (EditText) view;
                        editText.clearFocus();
                    }
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        return getWindow().superDispatchTouchEvent(ev) || onTouchEvent(ev);
    }

    public void showToast_boom(String text) {
        if (TextUtils.isEmpty(text)) return;
        Threadutils_boom.getInstance().runOnUiThread(() -> {
            if (toast_boom == null) toast_boom = Toast.makeText(this, text, Toast.LENGTH_SHORT);
            else toast_boom.setText(text);
            toast_boom.show();
        });
    }

    public void setBackBtn_boom(View btnView) {
        btnView.setOnClickListener(view -> onBackPressed());
    }

    public <T extends BaseActivity_boom> void startActivityForSingleTop_boom(Class<T> activityClass) {
        Intent intent = new Intent(this, activityClass);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity_boom(activityClass);
        finish();
    }

    public <T extends BaseActivity_boom> void startActivity_boom(Class<T> activityClass) {
        startActivity(new Intent(this, activityClass));
    }

    public <T extends BaseActivity_boom> void startActivity_boom(Class<T> activityClass,Product product) {
        startActivity(new Intent(this, activityClass).putExtra("product",product));
    }

    public void onUserProcessResponse(){

        //手机号后置校验
        if (ProcessInfo_boom.getInstance().isNeedVerification()){
            if (CountryInfo_boom.gInstance().isCambodia()) startActivity_boom(MobileVerificationActivity.class);
            else startActivity_boom(MobileVerificationActivity2.class);
            if (this instanceof LnApplyActivity_boom) finish();
            return;
        }

        startActivityForSingleTop_boom(LnMainActivity_boom.class);
    }

    public void afterPermission() {}

    public void onUserDataDelete(){
        //删除本地登录信息
        UserInfoHelper_boom.gInstance().sMobile("");
        UserInfoHelper_boom.gInstance().sToken("");
        UserInfoHelper_boom.gInstance().sUserId("");
        startActivityForSingleTop_boom(LoginPhoneNumActivity_boom.class);
    }

    public void showMsgDialog(String msg){
        new MsgDialog_boom(this,msg,5000, null).show();
    }

    public void startProcess(){
        startProcess(null);
    }

    public void startProcess(Product product){

        if (isClose()) return;

        if (product==null) product = Product.gtInstance(null);

        //手机号后置校验
        if (ProcessInfo_boom.getInstance().isNeedVerification()){
            if (CountryInfo_boom.gInstance().isCambodia()) startActivity_boom(MobileVerificationActivity.class);
            else startActivity_boom(MobileVerificationActivity2.class);
            return;
        }

        //权限
        if (!permissionRequestFlag && !Permissionutil_boom.checkAllPermissions(this)){
            if (allPermissionDialog==null){
                permissionRequestFlag = true;
                allPermissionDialog = new AllPermissionDialog_boom(this, () -> {
                    if (UserInfoHelper_boom.gInstance().gIsAdSource() && !Permissionutil_boom.checkAllPermissions(this)) finish();
                    else startProcess();
                });
                allPermissionDialog.show();
            }
            return;
        }

        if (allPermissionDialog!=null && allPermissionDialog.isShowing()) allPermissionDialog.dismiss();

        try {
            AnalyticsUtil_boom.INSTANCE.saveDeviceS2SInfo();
        }catch (Exception e){
            if (Constant_boom.Debug) e.printStackTrace();
        }

        //无流程
        if (ProcessInfo_boom.getInstance().gSteps().isEmpty()){
            applyProduct = product;
            HttpManager_boom.getInstance().requestLoanApplyDetail(applyProduct.gtProduct(),applyProduct.gtToken());
            return;
        }

        switch (ProcessInfo_boom.getInstance().gStepName(0)){
            case Process_Ocr -> //ocr流程
                startActivity_boom(OcrUpldActivity_boom.class,product);
            case Process_Sefie -> //人脸流程
                startActivity_boom(FaceUploadActivity_boom.class,product);
            case Process_Account -> {//绑卡流程
                //科特
                if (CountryInfo_boom.gInstance().isCote())
                    startActivity_boom(BdBkActActivity_Cote_boom.class, product);
                    //喀麦隆、塞内加尔
                else if ((CountryInfo_boom.gInstance().isFrench()))
                    startActivity_boom(BdBkActActivity_Fr_boom.class, product);
                    //其他国家
                else startActivity_boom(InfoUpldActivity_boom.class, product);
            }
            default -> startActivity_boom(InfoUpldActivity_boom.class,product);
        }

    }

    public void onLoanApplyDetailResponse(){
        startActivity_boom(LnApplyActivity_boom.class,applyProduct);
        if (this instanceof BaseInfoActivity_boom) finish();
    }

    public void onRepayDetailResponse(){
        if (isClose()) return;
        startActivity_boom(RepaymentActivity.class,repayProduct);
    }

    //获取bankAccountList返回(科特)
    public void onFetchBankAccountListResponse(){}

    public boolean isClose(){
        return isDestroyed() || isFinishing();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (allPermissionDialog!=null && allPermissionDialog.isShowing()) allPermissionDialog.dismiss();
    }

    protected void runWithCameraPermission(Runnable runnable){
        if (runnable==null || isClose()) return;
        if (Permissionutil_boom.checkPermissions(this, Manifest.permission.CAMERA)) runnable.run();
        else {
            new StatementDialog_boom(this,"CAMERA",() -> {
                runnableWithCameraPermission = runnable;
                EasyPermissions.requestPermissions(this, getString(R.string.launch_permissions_camera), Permission_Code_Camera, Manifest.permission.CAMERA);
            }).show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (allPermissionDialog!=null && allPermissionDialog.isShowing())
            allPermissionDialog.onPermissionsDenied(requestCode,perms);
        else if (requestCode==Permission_Code_Camera && runnableWithCameraPermission!=null){
            if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) new AppSettingsDialog.Builder(this).build().show();
            else UserInfoHelper_boom.gInstance().addEventPoint((pageTag + "_CAMERA_REQUEST_DENY_CLICK").toUpperCase());
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

        //tag2025
        if (allPermissionDialog==null){
            Log.w("permission=", "dialog is null" );
        }else if (!allPermissionDialog.isShowing()){
            Log.w("permission=", "dialog is not showing" );
        }else {
            Log.w("permission=", String.valueOf(requestCode) );
        }

        if (allPermissionDialog!=null && allPermissionDialog.isShowing())
            allPermissionDialog.onPermissionsGranted(requestCode,perms);
        else if (requestCode==Permission_Code_Camera && runnableWithCameraPermission!=null){
            UserInfoHelper_boom.gInstance().addEventPoint((pageTag + "_CAMERA_REQUEST_AGREE_CLICK").toUpperCase());
            runnableWithCameraPermission.run();
        }
    }

    @Override
    public void onRationaleDenied(int requestCode) {
        switch (requestCode){
            case Permission_Code_Camera -> UserInfoHelper_boom.gInstance().addEventPoint((pageTag + "_CAMERA_RATIONALE_DENY").toUpperCase());
            case Permission_Code_Sms -> UserInfoHelper_boom.gInstance().addEventPoint((pageTag + "_SMS_RATIONALE_DENY").toUpperCase());
        }
    }

    @Override
    public void onRationaleAccepted(int requestCode) {
        switch (requestCode){
            case Permission_Code_Sms -> {
                UserInfoHelper_boom.gInstance().addEventPoint((pageTag + "_SMS_RATIONALE_AGREE_CLICK").toUpperCase());
                EasyPermissions.requestPermissions(this, getString(R.string.launch_permissions_sms), Permission_Code_Sms, Manifest.permission.READ_SMS);
            }
            case Permission_Code_Camera -> {
                UserInfoHelper_boom.gInstance().addEventPoint((pageTag + "_CAMERA_RATIONALE_AGREE_CLICK").toUpperCase());
                EasyPermissions.requestPermissions(this, getString(R.string.launch_permissions_camera), Permission_Code_Camera, Manifest.permission.CAMERA);
            }
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        BaseApplication_boom.getInstant_boom().activityStarted();
    }

    @Override
    protected void onStop() {
        super.onStop();
        BaseApplication_boom.getInstant_boom().activityStopped();
        BaseApplication_boom.getInstant_boom().isActivityChangingConfigurations = isChangingConfigurations();
//        HttpManager_boom.getInstance().saveUserPointForBatch();
    }
}